package com.wdb007.venus.wss.factory;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wdb007.venus.wss.channelgroup.BookCaseChannelGroups;
import com.wdb007.venus.wss.channelgroup.ChannelGroups;
import com.wdb007.venus.wss.exception.SysErrException;
import com.wdb007.venus.wss.service.WebSocketServerService;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

public class WebSocketHandlerFactory {

	private Map<String, WebSocketServerService> map = new HashMap<String, WebSocketServerService>();
	
	private Logger logger = LoggerFactory.getLogger(WebSocketHandlerFactory.class);
	
	public WebSocketHandlerFactory(Map<String, WebSocketServerService> map) {
		this.map = map;
	}
	
	public String handle(ChannelHandlerContext ctx,String request) throws Exception{
		
		JSONObject jsonObj = JSON.parseObject(request);
		String action = jsonObj.getString("action");
		//logger.info("action:==== {}", action);
//		logger.info("action:==test== {}", action);
		if(null == action)
			throw new NullPointerException("action cannot be null");
		WebSocketServerService service = map.get(action);
		if(null == service)
			throw new SysErrException("action 没有对应的处理类");
		String response = null;
		try {
			response  = service.doService(ctx, request);
		}catch(Exception e) {
			logger.error("action["+action+"] 处理异常.", e);
		}
		return response;
	}
	/**
	 * 针对于异常做处理
	 * @param ctx
	 * @param cause
	 * @throws Exception
	 */
	public void close(ChannelHandlerContext ctx, Throwable cause)throws Exception{
		//FIXME
		logger.error("异常处理", cause);
		Channel channel = ctx.channel();
		if(ChannelGroups.contains(channel)) {
			ChannelGroups.discard(channel);
		}else if(BookCaseChannelGroups.contains(channel)) {
			BookCaseChannelGroups.discard(channel);
		}
	}
}
